var express = require('express');
var router = express.Router();
var mongoose = require('mongoose')
const Users = require('./../module/users')
require('./../util/util.js')

mongoose.connect('mongodb://http:127.0.0.1:27017/shopmall')

mongoose.connection.on('connected', () => {
  console.log('succcess and ok')
})

mongoose.connection.on('error', () => {
  console.log('error and failure')
})


//登录功能
router.post('/login',(req,res)=>{
  var params={
       userName:req.body.userName,
       userPwd:req.body.userPwd
  }
  Users.findOne(params,(error5,userdata)=>{ 
    if(error5){
     console.log('警告服务器错误')
    }else{
      if(userdata){
        console.log(userdata.userName)
        res.cookie('userId', userdata.userId, {
          path: '/',
          maxAge: 1000 * 60 * 60
        })
        
        res.cookie('userName',userdata.userName, {
          path: '/',
          maxAge: 1000 * 60 * 60
        })

        res.json({
          status:'0',
          mes:'',
          list:userdata.cartList
        })
      }else{
        res.json({
          status: '1',
          mes: '查无此用户',
          result: 'failure'
        })
      }
        
    }
  })
})

//登出功能
router.post('/logout',(req,res)=>{
  res.cookie('userId','',{
    path:'/',
    maxAge:-1
  })
  res.cookie('userName', '', {
    path: '/',
    maxAge: -1
  })
  res.json({
    status:'0',
    mes:'logOut success'
  })
})

//比较重要功能
router.get('/checklogin',(req,res)=>{
  if(req.cookies.userId){
    res.json({
      status:'0',
      mes:'',
      nickname:req.cookies.userName
    })
  }else{
    res.json({
      status:'1',
      mes:'当前未登录'
    })
  }
})

//得到购物车功能

router.get('/cart',(req,res)=>{
  var userId = req.cookies.userId
  Users.findOne({userId:userId},function(error,userdata) {
      if(error){
        console.log('出错啦')
      }else{
        if(userdata){
          res.json({
            status:0,
            mes:'',
            list:userdata.cartList
          })
        }
      }
  })
})


//删除功能

router.post('/cartDel',(req,res)=>{
  var productId = req.body.productId
  var userId = req.cookies.userId
  Users.update({
    userId:userId
    },{
    $pull:{
      'cartList':{
        productId:productId
      }
    }
    },function(error, doc) { 
    if(error){
      res.json({
        status: 0,
        mes: '删除成功'
      })
    }else{
        res.json({
          status:0,
          mes:'删除成功'
        })
      }
    });
})


//修改数量

router.post('/editcar',(req,res)=>{
  let productId = req.body.productId
  let checked = req.body.checked
  let productNum = req.body.num
  let userId = req.cookies.userId
  Users.update({'userId':userId,'cartList.productId':productId},{
    'cartList.$.productNum':productNum,
    'cartList.$.checked':checked
  },function (err,doc) {
    if(err){
      console.log('出错啦')
    }else{
      res.json({
        status:0,
        msg:'success and ok'
      })
    }
    
  })
})

//全选功能

router.get('/totalmoney',(req,res)=>{
  let userId = req.cookies.userId
  var checked = req.param('checked')?'1':'0'
  Users.findOne({userId:userId},(error,userdata)=>{
    if(error){
      res.json({
        status: 1,
        msg: 'select ALLerror',
      })
    }else{
      if(userdata){    
        userdata.cartList.forEach(item=>{
          item.checked = checked
        })
        userdata.save(function(error2,doc) {
          if(error2){
            console.log('保存出错啦')
          }else{
            res.json({
              status: 0,
              msg: 'success and ok',
            })
          }
        })
      }
    }
  })
})

//查询地址
router.get('/checkout',function(req,res) {
  let userId = req.cookies.userId
  Users.findOne({userId:userId},function (error,userdata) {
    if(error){
      res.json({
        status:'1',
        mes:'接口错误',
        result:''
      })
    }else{
      res.json({
        status: '0',
        mes: 'success and ok',
        data: userdata.addressList
      })
    }
  })
})

//修改默认地址

router.post('/setdefault',function(req,res) {
  let userId = req.cookies.userId
  let addressId = req.body.addressId
  Users.findOne({userId:userId},function (error,userdata) {
      if(error){
        res.json({
          status: '1',
          mes: '接口错误',
          result: ''
        })
      }else{
        if(userdata){
          userdata.addressList.forEach(item=>{
            
            if (item.addressId==addressId){
              item.isDefault = true
            }else{
              item.isDefault = false
            }
            console.log(item.isDefault)
          })
          userdata.save(function (error,doc) {
            if(error){
              res.json({
                status: '1',
                mes: '接口错误',
                result: ''
              })
            }else{
              res.json({
                status: '0',
                mes: '',
                result: 'success and ok'
              })
            }
          })
        }
      }
  })
})

//删除地址功能

router.get('/deladdress',function(req,res) {
  let userId = req.cookies.userId
  let addressId = req.param('addressId')
  console.log(addressId)
  Users.update({userId:userId
     },{
      $pull:{
        'addressList':{
          addressId:addressId
    }
  }
    },function (error,data) {
      if(error){
        res.json({
          status: '1',
          mes: '接口错误',
          result: ''
        })
      }else{
        res.json({
          status: '0',
          mes: '删除成功',
          result: ''
        })
      }
    })
})


//确认订单
router.post('/createOrder',function (req,res) {
  let userId=req.cookies.userId
  let addressId = req.body.addressId
  let orderTotal = req.body.total

  Users.findOne({userId:userId},function(error,userdata) {
    if(error){
      console.log('查询错误')
    }else{
      if(userdata){
        var buyshop=[]
        userdata.cartList.forEach(item=>{
            if(item.checked==1){
              buyshop.push(item)
            }
        })
        var buyaddress=userdata.addressList.filter(item=>{
          if(item.addressId==addressId){
            return item
          }
        })
        const shopmall = '622'
        var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss' )
        const r1 = Math.floor(Math.random() * 10)
        const r2 = Math.floor(Math.random() * 10) 
        var orderId = shopmall+r2+Date.now()+r1
      
        const order = {
          orderId:orderId,
          orderTotal:orderTotal,
          addressInfo:buyaddress[0],
          goodsList:buyshop,
          orderStatus:'1',
          createDate: createDate 
        }
        userdata.orderList.push(order)
        userdata.save(function (error,doc) {
          if(error){
            res.json({
              status: '1',
              mes: '接口错误',
              result: ''
            })
          }else{
            res.json({
              status: '0',
              mes: 'success and ok',
              result: orderId
            })
          }
        })
      }
    }
  })
})

//成功啦
router.get('/success',function (req,res) {
  let userId = req.cookies.userId
  let orderId = req.param('orderId')
  
  Users.findOne({userId:userId},function (error,userdata) {
      if(error){
        console.log('发生错误')
      }else{
        var orderTotal=''
        userdata.orderList.forEach(item=>{
          if (item.orderId == orderId){
            orderTotal = item.orderTotal
          }
        })
        res.json({
          status:'0',
          mes:'success and ok',
          result: orderTotal
        })
      }
  })
})

router.get('/smallcar',function(req,res) {
  let userId = req.cookies.userId 
  Users.findOne({userId:userId},function (error,userdata) {
    if(error){
      console.log('出处啦')
    }else{
          var count = 0
      userdata.cartList.forEach(item=>{
            if(item.checked==1){
              count++
            }
      })
          res.json({
            status:'0',
            mes:'success and ok',
            list:count
          }) 
    }
  })
})
//检测账号是否存在
router.post('/checkname',function (req,res) {
  let userName = req.body.userName
  Users.findOne({userName:userName},function (error,data) {
    if(error){
      console.log('666')
    }else{
      if(data){
        res.json({
          status:'0',
          mes:'账号已存在'
        })
      }else{
        res.json({
          status: '1',
          mes: '可以注册'
        })
      }
    }
  })
})


//注册成功功能
router.post('/okname',function (req,res) {
  const u2 = Math.floor(Math.random() * 10)
  const u1 = Math.floor(Math.random() * 10)
  const u3 = Date.now()
  var userId= u2+u1+u3  
  var userName = req.body.userName
  var userPwd = req.body.userPwd
  new Users({
    userName:userName,
    userPwd:userPwd,
    userId:userId,
    orderList:[],
    cartList:[],
    addressList:[]
  }).save(function (error,doc) {
    if(error){
      console.log('新增失败')
    }else{
      console.log('新增成功')
      res.json({
        status: '0',
        mes: '注册成功'
      })
    }
  })
})

module.exports = router;


// Users.update({
//   userId: userId
// }, {
//     $pull: {
//       'cartList': {
//         productId: productId
//       }
//     }
//   }, function (error, doc) {
//     if (error) {
//       res.json({
//         status: 0,
//         mes: '删除成功'
//       })
//     } else {
//       res.json({
//         status: 0,
//         mes: '删除成功'
//       })
//     }
//   });
// })